#!/usr/bin/env node

/**
 * MCP Unified Gateway
 * 
 * A universal gateway for aggregating multiple MCP servers
 */

import { Gateway } from './gateway/gateway';
import { ConfigLoader } from './config/config-loader';
import { AutoDiscovery } from './discovery/auto-discovery';
import { Logger } from './utils/logger';
import { CLI } from './cli/cli';

const logger = new Logger('main');

async function main() {
  try {
    // Check if running as CLI
    if (process.argv.length > 2) {
      const cli = new CLI();
      await cli.run(process.argv.slice(2));
      return;
    }

    // Load configuration
    const configLoader = new ConfigLoader();
    const config = await configLoader.load();

    // Discover available servers
    const discovery = new AutoDiscovery(config);
    const servers = await discovery.discover();

    logger.info(`Discovered ${servers.length} MCP servers`);

    // Start gateway
    const gateway = new Gateway(config, servers);
    await gateway.start();

    // Handle shutdown
    process.on('SIGINT', async () => {
      logger.info('Shutting down gateway...');
      await gateway.stop();
      process.exit(0);
    });

    process.on('SIGTERM', async () => {
      logger.info('Shutting down gateway...');
      await gateway.stop();
      process.exit(0);
    });

  } catch (error) {
    logger.error('Failed to start gateway:', error);
    process.exit(1);
  }
}

// Run if executed directly
if (require.main === module) {
  main();
}

export { Gateway, ConfigLoader, AutoDiscovery, Logger };